/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-03-23
*/
package com.rzico.article.service;

import com.rzico.article.entity.ArticleTag;
import com.rzico.base.BaseMapper;
import com.rzico.base.impl.BaseServiceImpl;
import com.rzico.article.entity.Article;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.service.EnterpriseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.rzico.article.mapper.ArticleMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <pre>
 * 文章管理业务类
 * </pre>
 *
 * @author Rzico Boot
 * @version 1.0
 */
@Service
public class ArticleService extends BaseServiceImpl<Article, String> {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private ArticleTagService articleTagService;



    @Override
    public BaseMapper<Article, String> getMapper() {
        return articleMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    public Article save(Article article,Long[] tagIds) {

        Enterprise enterprise = enterpriseService.getCurrent();


        article.setEnterpriseId(enterprise.getId());
        article.setCreateDate(new Date());

        article.setDeleted(false);
        super.insertUseGeneratedKeys(article);


        if (tagIds!=null) {
            for (Long tagId : tagIds) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticles(article.getId());
                articleTag.setTags(tagId);
                articleTagService.insert(articleTag);

            }
        }


        return article;
    }


    @Transactional(rollbackFor = Exception.class)
    public Article update(Article article,Long [] tagIds) {

        super.updateByPrimaryKeySelective(article);

        ArticleTag articleTag = new ArticleTag();
        articleTag.setArticles(article.getId());
        articleTagService.delete(articleTag);

        if (tagIds!=null) {

            for (Long tagId : tagIds) {
                articleTag = new ArticleTag();
                articleTag.setArticles(article.getId());
                articleTag.setTags(tagId);
                articleTagService.insert(articleTag);

            }
        }

        return article;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteByIds(Object[] ids) {
        int rw = 0;
        for (Object id:ids) {
            Article article = selectByPrimaryKey(id);
            article.setDeleted(true);
            rw = rw + super.updateByPrimaryKeySelective(article);
        }
        return rw;
    }

}
